package com.ott.iot_client_demo.service;

import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.ClientException;
import com.aliyun.mns.common.ServiceException;
import com.aliyun.mns.model.Message;
import com.ott.iot_client_demo.bean.AliAcountBean;
import com.ott.iot_client_demo.bean.QueueMessageBean;
import com.ott.iot_client_demo.utils.JacksonUtil;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ComsumerQueueService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AliAcountBean aliAcountBean;

    public void initServer() {
        CloudAccount account = new CloudAccount(
                aliAcountBean.getAccessKeyId(),
                aliAcountBean.getAccessKeySecret(),
                aliAcountBean.getAccountEndpoint());
        MNSClient client = account.getMNSClient(); //this client need only initialize once

        try {
            CloudQueue queue = client.getQueueRef("aliyun-iot-"+aliAcountBean.getProductKey());// replace with your queue name
            while (true) {
                // 获取消息
                Message popMsg = queue.popMessage(10); //长轮询等待时间为10秒
                if (popMsg != null) {
//                    logger.info("获取消息内容"+popMsg.getMessageBodyAsRawString());//获取原始消息
                    System.out.println(popMsg.getMessageBody());
                    QueueMessageBean queueMessageBean = JacksonUtil.readValue(popMsg.getMessageBody(),QueueMessageBean.class);
                    String payload = queueMessageBean.getPayload();
                    if(payload != null){
                        byte[] b = Base64.decodeBase64(payload);
                        logger.info("经|纬:"+new String(b));
                    }

                    queue.deleteMessage(popMsg.getReceiptHandle()); //从队列中删除消息
                } else {
                    logger.info("MNS消息服务空闲中");
                }
            }
        } catch (ClientException ce) {
            logger.error("与阿里云 MNS 服务连接出错，请确认网络和DNS状态:");
            ce.printStackTrace();
        } catch (ServiceException se) {
            if (se.getErrorCode().equals("QueueNotExist")) {
                logger.error("MNS 消息队列不存在，请先创建再使用。");
            } else if (se.getErrorCode().equals("TimeExpired")) {
                logger.error("请求过期，请检查本地计算机时间");
            }
            /*
            you can get more MNS service error code in following link.
            https://help.aliyun.com/document_detail/mns/api_reference/error_code/error_code.html?spm=5176.docmns/api_reference/error_code/error_response
            */
            se.printStackTrace();
        } catch (Exception e) {
            System.out.println("Unknown exception happened!");
            e.printStackTrace();
        }

        client.close();
    }
    /**
     * @see byte[]数组转换为String字符串
     * @author Herman.Xiong
     * @date 2014年5月5日 17:15:42
     * @param data byte数组
     * @return String 转换后的字符串
     */
    public  String byteToArray(byte[]data){
        String result="";
        for (int i = 0; i < data.length; i++) {
            result+=Integer.toHexString((data[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3);
        }
        return result;
    }
}

